package com.bluexmicro.android.ota

import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

object FileUtils {

    /**
     * clear file folder
     * @param path
     */
    private fun delete(path: String) {
        val file = File(path)
        val files = file.listFiles()
        if (files != null && files.isNotEmpty()) {
            for (temp in files) {
                if (temp.isFile) {
                    temp.delete()
                }
                if (temp.isDirectory) {
                    delete(temp.absolutePath)
                    temp.delete()
                }
            }
        }
    }

    /**
     * 这里只做解压,并
     *
     *
     * 真实项目的做法
     * 1. 计算文件hash判断本地是否存在同样的hash的文件夹，如果有说明之前已经用过同样的压缩包，跳过解压，直接使用
     * 2. 如果无，解压
     * 3. 使用刚解压的新文件
     */
    fun unzipFile(context: Context, zipPath: String): List<File> {
        val TAG = "BX-OTA"
        val otaCacheDir = "${context.cacheDir}${File.separator}PartTableDir${File.separator}"
        val dir = File(otaCacheDir)
        if (dir.exists()) {
            delete(otaCacheDir)
        } else {
            dir.mkdirs()
        }
        val outputFiles = mutableListOf<File>()
        val inputStream = FileInputStream(zipPath)
        val zipInputStream = ZipInputStream(inputStream)
        var fos: FileOutputStream? = null
        try {
            val buffer = ByteArray(1024 * 1024)
            var count: Int
            var zipEntry: ZipEntry?
            while (zipInputStream.nextEntry.also { zipEntry = it } != null) {
                if (!zipEntry!!.isDirectory) {
                    var fileName = zipEntry!!.name
                    fileName = fileName.substring(fileName.lastIndexOf('/') + 1)
                    Log.d(TAG, "解压到${otaCacheDir}${fileName}")
                    val file = File("${otaCacheDir}${fileName}")
                    file.createNewFile()
                    fos = FileOutputStream(file)
                    while ((zipInputStream.read(buffer).also { count = it }) > 0) {
                        fos.write(buffer, 0, count)
                    }
                    fos.close()
                    if (file.isHidden) {
                        //苹果系统会产生隐藏文件
                        file.delete()
                    } else {
                        Log.d(TAG, "有效文件：${otaCacheDir}${fileName}")
                        outputFiles.add(file)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream.close()
            zipInputStream.close()
            fos?.close()
        }
        return outputFiles
    }

}